'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { page = 1, pageSize = 20, keyword = '', action = '' } = event;
    const { OPENID } = context;
    
    // 验证管理员权限
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        is_active: true
      })
      .field({
        _id: 1,
        username: 1,
        role: 1
      })
      .get();
    
    if (adminInfo.data.length === 0) {
      return {
        code: 403,
        message: '您没有管理员权限'
      };
    }
    
    // 构建查询条件
    const query = {};
    
    // 添加关键词搜索条件
    if (keyword) {
      query.$or = [
        { admin_name: db.RegExp({
          regexp: keyword,
          options: 'i'
        }) },
        { target_name: db.RegExp({
          regexp: keyword,
          options: 'i'
        }) },
        { message: db.RegExp({
          regexp: keyword,
          options: 'i'
        }) },
        { target_title: db.RegExp({
          regexp: keyword,
          options: 'i'
        }) }
      ];
    }
    
    // 添加操作类型筛选条件
    if (action) {
      query.action = action;
    }
    
    // 计算分页参数
    const skip = (page - 1) * pageSize;
    
    // 执行查询
    const logsResult = await db.collection('admin_logs')
      .where(query)
      .skip(skip)
      .limit(pageSize)
      .orderBy('create_time', 'desc')
      .get();
    
    return {
      code: 0,
      message: '获取管理员日志成功',
      data: logsResult.data
    };
    
  } catch (error) {
    console.error('获取管理员日志失败:', error);
    return {
      code: 500,
      message: '获取管理员日志失败，请稍后重试',
      error: error.message
    };
  }
};